# 任务：预测x=3.5对应的y值
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression  # 线性回归模型
from sklearn.metrics import mean_squared_error, r2_score  # 均方差和R2分数

# 读入数据
data = pd.read_csv('generated_data.csv')
# print(笔记.md)
x = data.loc[:, 'x']
y = data.loc[:, 'y']
# print(x,y)
# 展示图形
plt.scatter(x, y)
plt.figure(figsize=(20, 20))
plt.show()

# 转换数据
x = np.array(x)
x = x.reshape(-1, 1)
y = np.array(y)
y = y.reshape(-1, 1)

# 实例化线性回归模型
lr_model = LinearRegression()
# 训练模型
lr_model.fit(x, y)
y_predict = lr_model.predict([[3.5]])
print(y_predict)

# 打印a,b
print(lr_model.coef_)  # a
print(lr_model.intercept_)  # b

# 评估模型
mse = mean_squared_error(y, lr_model.predict(x))
r2 = r2_score(y, lr_model.predict(x))
print('均方差:', mse)
print('R2分数:', r2)
